<template>
  <!-- 页面-租户管理-添加/編輯 -->
  <div>
    <Spin size="large" fix v-if="spinShow"></Spin>
    <Form :model="modelForm" ref="editForm" :rules="rule" :label-width="80">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <!-- 租户编码 -->
          <Form-item prop="tenantCode" :label="$t('module.tenantManage.tenantCode')">
            <Input
              v-model.trim="modelForm.tenantCode"
              :placeholder="$t('module.tenantManage.placeholder.tenantCode')"
              :disabled="isReadyOnly"
            />
          </Form-item>
        </Col>
        <Col span="12">
          <!-- 租户名称 -->
          <Form-item prop="tenantName" :label="$t('module.tenantManage.tenantName')">
            <Input
              v-model.trim="modelForm.tenantName"
              :placeholder="$t('module.tenantManage.placeholder.tenantName')"
              :maxlength="100"
            />
          </Form-item>
        </Col>
                <Col span="12">
          <!-- 租户类型 -->
          <Form-item prop="tenantType" :label="$t('module.tenantManage.tenantType')">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.tenantType')"
              v-model="modelForm.tenantType"
              :transfer="true"
              class="no-borderColor"
              :disabled="isReadyOnly"
            >
              <Option
                :value="1"
                :key="1"
              >{{ $t("module.tenantManage.tenantTypeItem.groupCompany") }}</Option>
              <Option :value="2" :key="2">{{ $t("module.tenantManage.tenantTypeItem.company") }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border: none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" style="width: 90%;" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <!-- 默认用户中心 -->
        <!-- <Col span="12">
          <Form-item
            prop="defaultUserRepository"
            :label="$t('module.tenantManage.defaultUserRepository')"
          >
            <Select
              :placeholder="$t('module.tenantManage.placeholder.defaultUserCenter')"
              v-model="modelForm.defaultUserRepository"
              :transfer="true"
              class="no-borderColor"
            >
              <Option
                v-for="itemKey in Object.keys(userRepositorys)"
                :value="itemKey"
                :key="itemKey"
              >
                {{
                userRepositorys[itemKey]
                }}
              </Option>
            </Select>
          </Form-item>
        </Col>-->
                <Col span="12" style="border: none;">
          <Form-item prop="openTime" :label="$t('module.tenantManage.effectBeginTime')">
            <DatePicker
              type="date"
              ref="openTime"
              :placeholder="$t('module.tenantManage.selectDate')"
              :value="modelForm.openTime"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border: none;">
          <Form-item prop="expireTime" :label="$t('module.tenantManage.effectEndTime')">
            <DatePicker
              type="date"
              ref="expireTime"
              :placeholder="$t('module.tenantManage.permanent')"
              :value="modelForm.expireTime"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <!-- <Row :gutter="32" class="code-row-bg"> -->
        <!-- <Col span="12"> -->
          <!-- 租户类型 -->
          <!-- <Form-item prop="tenantType" :label="$t('module.tenantManage.tenantType')">
            <Select
              :placeholder="$t('module.tenantManage.placeholder.tenantType')"
              v-model="modelForm.tenantType"
              :transfer="true"
              class="no-borderColor"
              :disabled="isReadyOnly"
            >
              <Option
                :value="1"
                :key="1"
              >{{ $t("module.tenantManage.tenantTypeItem.groupCompany") }}</Option>
              <Option :value="2" :key="2">{{ $t("module.tenantManage.tenantTypeItem.company") }}</Option>
            </Select>
          </Form-item>
        </Col> -->
        <!-- <Col span="12" style="border: none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" style="width: 90%;" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col> -->
        <!-- 默认用户中心 -->
        <!-- <Col span="12">
          <Form-item
            prop="defaultUserRepository"
            :label="$t('module.tenantManage.defaultUserRepository')"
          >
            <Select
              :placeholder="$t('module.tenantManage.placeholder.defaultUserCenter')"
              v-model="modelForm.defaultUserRepository"
              :transfer="true"
              class="no-borderColor"
            >
              <Option
                v-for="itemKey in Object.keys(userRepositorys)"
                :value="itemKey"
                :key="itemKey"
              >
                {{
                userRepositorys[itemKey]
                }}
              </Option>
            </Select>
          </Form-item>
        </Col>-->
      <!-- </Row> -->
      <!-- <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none;">
          <Form-item prop="openTime" :label="$t('module.tenantManage.effectBeginTime')">
            <DatePicker
              type="date"
              ref="openTime"
              :placeholder="$t('module.tenantManage.selectDate')"
              :value="modelForm.openTime"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12" style="border: none;">
          <Form-item prop="expireTime" :label="$t('module.tenantManage.effectEndTime')">
            <DatePicker
              type="date"
              ref="expireTime"
              :placeholder="$t('module.tenantManage.permanent')"
              :value="modelForm.expireTime"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 100%;"
            ></DatePicker>
          </Form-item>
        </Col>
      </Row> -->
      <!-- <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" style="width: 90%;" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>-->
      <!-- v-if="appLication.data.length" -->
      <!-- <Divider orientation="left">{{ $t("module.tenantManage.allotApp") }}</Divider> -->
      <!-- 分配应用 列表 -->
      <!-- <div class="allot-apply-table">
        <Table 
          max-height="233" 
          :columns="appLication.columns" 
          :data="appLication.data"
          @on-select="selectAllotApply"
          @on-select-cancel="selectAllotApply"
          @on-select-all="selectAllotApply"
          @on-select-all-cancel="selectAllotApply"
        ></Table>
      </div>-->
    </Form>
    <!-- 分配应用(外面包一层tab处理屏幕放大125%时多选框消失问题) -->
    <Tabs class="tenetTab">
      <TabPane>
        <allot-app
          :appLication="appLication"
          @handleSearchAllotApp="getSearchAllotApp"
          @handleAllotApp="getSelectAllotApp"
        />
      </TabPane>
    </Tabs>
  </div>
</template>
<script>
import {
  getTenantById,
  saveOrUpdateTenant,
  findApplicationList,
  getTenantApplicationList
} from "@/api/teantManageAPI.js";
import locales from "./locales.js";
import AllotApp from "./AllotApp"; // 分配应用
import { RIPPLES_APP } from "@/const.js";
// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  name: "tenantedit",
  mixins: [locales],
  components: {
    AllotApp
  },
  data() {
    const validateTenantCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.tenantManage.entertenantCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp("^([a-zA-Z0-9]|_|-|\\.)+$").test(value)) {
        callback(new Error(this.$t("module.tenantManage.warning.codeFormat")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const validateUsefulLife = (rule, value, callback) => {
      if (value[0] === "") {
        callback(new Error(this.$t("module.tenantManage.enterUsefulLife")));
      } else {
        callback();
      }
    };
    const validateTenantType = (rule, value, callback) => {
      callback();
    };
    return {
      tenantCode: "", //当前登录用户租户编码
      appLication: {
        columns: [
          {
            type: "selection",
            width: 60,
            align: "center"
          },
          {
            title: this.$t("module.tenantManage.appCode"),
            key: "clientId"
          },
          {
            title: this.$t("module.tenantManage.appNameGuess"),
            key: "appName"
          }
        ],
        data: []
      },
      spinShow: true,
      isReadyOnly: false,
      loginmodes: {},
      productType: {},
      // 保存初始数据
      initData: {
        enabled: ""
      },
      // 取消选中的数据
      cancelSelectApp: [],
      // 暂存应用的数据
      // modelFormApp: [],
      // 标识当前是否是搜索查询
      isSearch: "",
      // 初始的选中数据
      selectApp: [],
      modelForm: {
        // defaultUserRepository: "",
        tenantCode: "",
        tenantName: "",
        tenantType: 1,
        openTime: "",
        expireTime: "",
        // usefulLife: [],
        enabled: 1,
        applicationCodes: []
      },
      rule: {
        // defaultUserRepository: [
        //   {
        //     required: true,
        //     message: this.$t("module.tenantManage.enterdefaultUserRepository"),
        //     trigger: "change"
        //   }
        // ],
        tenantName: [
          {
            required: true,
            message: this.$t("module.tenantManage.entertenantName"),
            trigger: "blur"
          },
          {
            type: 'string',
            max: 64,
            message: this.$t("common.warning.lengMaxFormat", ['64'])
          },
          {
            type: 'string',
            pattern: /[\u4E00-\u9FA5]|[A-Z]|[a-z]|[0-9]/,
            message: this.$t("common.warning.nameFormat")
          }
        ],
        tenantCode: [
          {
            required: true,
            validator: validateTenantCode,
            trigger: "blur"
          },
          {
            type: 'string',
            max: 30,
            message: this.$t("common.warning.lengMaxFormat", ['30'])
          }, 
          {
            type: 'string',
            pattern: /^[a-zA-Z0-9|_|\-|\.]+$/,
            message: this.$t("common.warning.codeFormat")
          }
        ],
        tenantType: [
          {
            required: true,
            validator: validateTenantType,
            trigger: "blur"
          }
        ],
        usefulLife: [
          {
            required: true,
            validator: validateUsefulLife,
            trigger: "change"
          }
        ],
        openTime: [{ required: true, type: "string", trigger: "change" }],
        expireTime: [{ required: true, type: "string", trigger: "change" }]
      }
    };
  },
  props: {
    tenantInfo: {
      type: Object,
      default: () => ({})
    },
    rowList: {
      type: Object,
      default: () => ({})
    },
    userRepositorys: Object
  },
  computed: {
    actions() {
      return [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          // theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ];
    },
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.expireTime == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.modelForm.expireTime.valueOf() - ONE_DAY
            );
          } else if (typeof _this.modelForm.expireTime == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.expireTime.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.modelForm.openTime == "object") {
            // 生效日期是日期对象，如 new Date()

            // debugger
            return date && date.valueOf() < _this.modelForm.openTime.valueOf() - ONE_DAY;
          } else if (typeof _this.modelForm.openTime == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.modelForm.openTime.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created: function() {
    this.getNowTenantCode();
    if (this.tenantInfo.id) {
      // 编辑
      this.$emit("SetTitle", this.$t("module.tenantManage.editTenant"));
      this.isReadyOnly = true;
    } else {
      this.$emit("SetTitle", this.$t("module.tenantManage.createTenant"));
      this.findApplicationList();
    }
    this.$emit("SetPageWidth", 734);
    this.$emit("SetPageActions", this.actions);
    this.queryUserData();
  },
  methods: {
    // 查询租户编码
    getNowTenantCode() {
      this.userInfo = $store.state["ripples-components"].userInfo;
      if (!this.userInfo) return;
      // 根据当前角色查询租户编码
      this.tenantCode = this.userInfo.tenantCode;
    },
    // 搜索分配应用
    getSearchAllotApp(data, searchOrReset) {
      // 查询后取消该应用，重置时该应用被取消了，没有重置回选中，需调重新获取选中数据
      if (searchOrReset == "reset") {
        // this.getDataById();
        this.modelForm.applicationCodes = [...this.selectApp];
        this.findApplicationList();
        return;
      }
      this.findApplicationList(data.nameOrCode);
    },
    // 获取应用列表数据
    findApplicationList(nameOrCode = null) {
      // 获取应用列表数据
      findApplicationList({ tenantCode: this.tenantCode, enabled: null, nameOrCode: nameOrCode })
        .then(response => {
          let { status, data } = response;
          if (status === 200) {
            // 编辑
            if (this.tenantInfo.id) {
              if (data && data.length) {
                for (let i = 0; i < data.length; i++) {
                  let item = data[i];
                  if (this.modelForm.applicationCodes.indexOf(item.clientId) !== -1) {
                    item._checked = true;
                    continue;
                  }
                }
              }
            }
            // 过滤掉未选中的无效应用
            let allotAppData = data.filter(item => item.enabled == 1 || item._checked == true);
            // 默认分配Ripples应用/表单平台，不可取消
            const defaultSelectList = []
            let defaultSelectTypeList = [2,3]
            allotAppData.find((app, index) => {
              if (defaultSelectTypeList.includes(app.appType)) {
                // 新增时
                if (!this.tenantInfo.id) {
                  app._checked = true;
                  defaultSelectList.push(app.clientId)
                  // 把Ripples应用设置到选中集合
                  this.getSelectAllotApp(defaultSelectList);
                  app._disabled = true;
                } else {
                  if (this.selectApp.find(item => item === app.clientId)) {
                    app._disabled = true;
                  }
                }
                // Ripples应用排第一个
                allotAppData.splice(index, 1);
                allotAppData.unshift(app);
              }
              // if (app.clientId == "online-report") {
                
              // }
            });
            // 排序：将已选应用排于未选应用前
            this.appLication.data = this.$root.$options.filters["sort-checkedAppFirst"](allotAppData);
            // 标识当前是否是搜索查询
            this.isSearch = nameOrCode ? "search" : "";
          }
          this.spinShow = false;
        })
        .catch(() => {
          this.spinShow = false;
        });
    },
    getDataById() {
      getTenantById(this.tenantInfo.id)
        .then(res => {
          // 保存初始状态
          this.initData.enabled = res.data.enabled;
          this.modelForm.applicationCodes = res.data.applicationCodes;
          // 保存初始的选中数据
          this.selectApp = [...res.data.applicationCodes];
          this.findApplicationList();
        })
        .catch(err => {
          this.$message.error({
            content: err.message,
            duration: 3
          });
          this.spinShow = false;
        });
    },
    queryUserData() {
      this.spinShow = true;
      //获取用户中心列表
      if (!!this.tenantInfo.id) {
        // this.modelForm.defaultUserRepository = this.rowList.defaultUserRepository;
        this.modelForm.tenantCode = this.rowList.tenantCode;
        this.modelForm.tenantName = this.rowList.tenantName;
        this.modelForm.tenantType = this.rowList.tenantType;
        this.modelForm.openTime = this.formatDateTime(this.rowList.openTime);
        this.modelForm.expireTime = this.rowList.expireTime == null ? "" : this.formatDateTime(this.rowList.expireTime);
        this.modelForm.enabled = this.rowList.enabled;
        this.modelForm.id = this.rowList.id;
        this.getDataById();
      } else {
        // 默认有效期
        this.modelForm.openTime = new Date()
          .toISOString()
          .replace(/T.*/, " ")
          .trim();
        this.modelForm.expireTime = "2099-12-31";
      }
    },
    // 保存、修改租户
    saveOrUpdateTenant() {
      this.actions[0].loading = true;
      saveOrUpdateTenant(this.modelForm)
        .then(res => {
          this.actions[0].loading = false;
          const content = this.tenantInfo.id
            ? this.$t("module.receiptSequence.updateSuccess")
            : this.$t("module.receiptSequence.createSuccess");
          this.$message.success({
            content: content,
            duration: 3
          });
          this.$emit("Close", true);
        })
        .catch(error => {
          this.actions[0].loading = false;
        });
    },
    save() {
      // this.modelForm.applicationCodes = this.modelFormApp;
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          // 初始状态为有效
          if (this.initData.enabled == 1) {
            let warningText;
            if (this.modelForm.enabled == 0) {
              // 更改为无效时的提示
              warningText = this.$t("module.tenantManage.warning.disableTenant");
            } else if (this.cancelSelectApp.length != 0) {
              // 取消分配的有效应用的提示
              let cancelApp = [];
              this.cancelSelectApp.map(item => {
                cancelApp.push(item.appName);
              });
              warningText = this.$t("module.tenantManage.warning.cancelApp") + "\n" + "[" + cancelApp + "]";
            }
            if (warningText) {
              // 删除提示级别：严重
              this.$confirm
                .swarning(warningText)
                .then(() => {
                  this.saveOrUpdateTenant();
                })
                .catch(_ => _);
            } else {
              this.saveOrUpdateTenant();
            }
          } else {
            this.saveOrUpdateTenant();
          }
        } else {
          // 错误提示： 表单验证未通过，请修改
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    // 获取取消选择的数据
    getSelectAllotApp(selection) {
      // this.modelForm.applicationCodes = selection;
      // this.appLication.data为初始所有应用(包含选中与未选)，selection为选中应用
      // 取消选中的数据（包括有效无效）
      let allCancelSelectApp = [];
      // 取消选中的数据（只包括有效）
      this.cancelSelectApp = [];
      // 所有应用数据
      let allApp = this.appLication.data;
      allApp.filter(item => {
        // 初始应用中的选中的应用
        if (item._checked) {
          // 选中应用在初始应用中未存在，则代表应用已被取消，并且该取消的应用为有效应用
          // if (selection.indexOf(item.clientId) == -1 && item.enabled == 1) {
          //   this.cancelSelectApp.push(item);
          // }
          if (selection.indexOf(item.clientId) == -1) {
            allCancelSelectApp.push(item.clientId);
            if (item.enabled == 1) {
              this.cancelSelectApp.push(item);
            }
          }
        }
      });
      // 标识当前是否是搜索查询：如果是搜索查询才调用此方法去处理“查询的数据进行取消或新增时，原来选择的数据会被置空”问题
      if (this.isSearch) {
        // 参数1为选中数据，参数2为取消的数据
        this.cancelOrAdd(selection, allCancelSelectApp);
      } else {
        this.modelForm.applicationCodes = selection;
      }
    },
    // 当针对查询的数据进行取消或新增时，原来选择的数据会被置空，因此把新数据与原数据进行合并去重处理
    cancelOrAdd(selection, allCancelSelectApp) {
      // 原来的选中数据
      let applicationCodes = this.modelForm.applicationCodes;
      // 如存在新增数据
      if (selection.length != 0) {
        let data = applicationCodes.concat(selection);
        applicationCodes = Array.from(new Set(data));
      }
      // 如存在取消数据
      if (allCancelSelectApp.length != 0) {
        applicationCodes.map((item, index) => {
          if (allCancelSelectApp.indexOf(item) != -1) {
            applicationCodes.splice(index, 1);
          }
        });
      }
      this.modelForm.applicationCodes = applicationCodes;
      // this.modelFormApp = applicationCodes;
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },
    onStartDateChange(date) {
      this.modelForm.openTime = date;
    },
    onEndDateChange(date) {
      this.modelForm.expireTime = date;
    }
  },
  watch: {},
  directives: {}
};
</script>

<style lang="less">
.useful-life-wrap {
  .ivu-date-picker {
    width: 100%;
  }
}
.tenetTab {
  .ivu-tabs-bar {
    display: none;
  }
}
</style>
